package com.fingard.dsp.bank.directbank.vbao02;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.math.BigDecimal;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IStatement;
import com.fingard.dsp.bank.reqrespobj.statement.ReqQryStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RetAtsStatement;
import com.fingard.dsp.bank.reqrespobj.statement.TransState;
import com.fingard.dsp.bank.reqrespobj.statement.detail.RetAtsStatementDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;

/**
 * 微保对账单
 *     v5_5.1支持:
 *          1、单笔代收付
 *          2、批量代收付
 * @author cruise
 * @date 2018/6/21
 * @modify 2018/6/22 version 1.0
 */
public class VBAO02Statement extends VBAO02Base implements IStatement {
	@Override
	public RetAtsStatement d_Qry_Statement(ReqQryStatement p_reqQrySttm) throws Exception {
		RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
        retAts.writeStart();

        String[] batRecPayRespHeader = getBatRecPayStatement(p_reqQrySttm, retAts);

        String batRecPayTotalNum = retAts.totalNum;
        if ("".equals(batRecPayTotalNum)) {
        	batRecPayTotalNum = "0";
        }

        String[] singlePayRecRespHeader = singlePayRecStatement(p_reqQrySttm, retAts);

        String singlePayRecTotalNum = retAts.totalNum;
        if ("".equals(singlePayRecTotalNum)) {
            singlePayRecTotalNum = "0";
        }

        if ("-1".equals(batRecPayRespHeader[0]) && "-1".equals(singlePayRecRespHeader[0])) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(batRecPayRespHeader[1] + ";" + singlePayRecRespHeader[1]);
        } else {
            // 获取成功时写入总笔数
            int totalNum = Integer.parseInt(batRecPayTotalNum) + Integer.parseInt(singlePayRecTotalNum);
            retAts.isWritedTotalNum(String.valueOf(totalNum));
        }

        retAts.writeEnd();
        return retAts;
	}
	
	private String[] getBatRecPayStatement(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) throws Exception {
		String[] respHeader = new String[]{"",""};
		
		retAts.totalNum = "0";
		String respCode = "";
		String respInfo = "";
		
		try {
			ActSetItem actItem = getBankConfig().getActSetItem(p_reqQrySttm.actNum, "");
			if (actItem != null) {
				FtpSet ftpSet = bankFront.getFtpSet("");
				
				WriteBankLogLn2("微保批量代收付对账单SFTP服务器地址:" + ftpSet.serverIP + ":" + ftpSet.port);
				
				String downFileName = actItem.merchantId + "_" + p_reqQrySttm.busDate + "_BATCH.txt";
				WriteBankLogLn2("微保批量代收付对账单所在服务器路径:" + getSFTPDir(ftpSet.downDir) + actItem.merchantId + "/" + downFileName);
				
	            String localFilePath = createTempFileDirectory() + File.separator + downFileName;
	            WriteBankLogLn2("微保批量代收付对账单保存本地路径:" + localFilePath);
				
				SftpPortClient sftp = new SftpPortClient(ftpSet);
	            FtpReceiver ftpReceiver = sftp.downloadFile(actItem.merchantId + "/", downFileName, localFilePath);
	            if (ftpReceiver.isCompleted) {
	            	WriteBankLogLn2("微保批量代收付对账单下载成功!");
	            	
	            	String tmpStrRet = FileHelper.readFileText(localFilePath, getCharset());
	            	WriteBankLogLn2("微保批量代收付对账单响应数据:\r\n" + tmpStrRet);
	            	if (StringHelper.hasAnyChar(tmpStrRet)) {
	            		StringReader strReader = new StringReader(tmpStrRet);
						BufferedReader tmpReader = new BufferedReader(strReader);
						
						String totalLine = tmpReader.readLine();
						String[] totalArr = totalLine.split("\\|");
						
						String recTotalNum = totalArr[2];
						if ("".equals(recTotalNum)) {
							recTotalNum = "0";
						}
						String payTotalNum = totalArr[4];
						if ("".equals(payTotalNum)) {
							payTotalNum = "0";
						}
						
						retAts.totalNum = String.valueOf(Long.parseLong(recTotalNum) + Long.parseLong(payTotalNum));
						
						while(true) {
							String eachline = tmpReader.readLine();
							if(eachline == null){
								break;
							}
							
							String[] detailNodes = eachline.split("\\^");
							if ("1".equals(detailNodes[11])) {
								RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();
								
								if (StringHelper.hasAnyChar(detailNodes[3])) {
									tmpRetDetail.askNumber = detailNodes[3];
								}
								
								if (StringHelper.hasAnyChar(detailNodes[2])) {
									tmpRetDetail.reqBatchNO = detailNodes[2];
								}
								
								if (StringHelper.hasAnyChar(detailNodes[3])) {
									String busType = detailNodes[3];
									if ("1".equals(busType)) {
										tmpRetDetail.cdFlag = "22";
									} else {
										tmpRetDetail.cdFlag = "27";
									}
								}
								
								if (StringHelper.hasAnyChar(detailNodes[4])) {
									tmpRetDetail.amount = detailNodes[4];
								}
								
								tmpRetDetail.busTime = Format.DateTime14Format.format(p_reqQrySttm.getBusDate());
								
								if (StringHelper.hasAnyChar(detailNodes[8])) {
									tmpRetDetail.oppAct = detailNodes[8];
								}
								
								if (StringHelper.hasAnyChar(detailNodes[5])) {
									tmpRetDetail.oppActName = detailNodes[5];
								}
								
								tmpRetDetail.transState = TransState.Success;
			    				
				        		retAts.writeRetDetail(tmpRetDetail);
							}
						}
	            	} else {
	            		respCode = "-1";
		    			respInfo = "微保批量代收付对账单内容为空,请联系微保相关技术人员!";
	            	}
	            } else {
	            	respCode = "-1";
	    			respInfo = "微保批量代收付对账单下载失败,原因:\r\n" + ftpReceiver.connMsg;
	            }
			} else {
				respCode = "-1";
				respInfo = "未找到账号[" + p_reqQrySttm.actNum + "]商户配置信息";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			respCode = "-1";
			respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		respHeader[0] = respCode;
		respHeader[1] = respInfo;
		
		return respHeader;
	}
	
	private String[] singlePayRecStatement(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) throws Exception {
		String[] respHeader = new String[]{"",""};
		
		retAts.totalNum = "0";
		String respCode = "";
		String respInfo = "";
		
		try {
			ActSetItem actItem = getBankConfig().getActSetItem(p_reqQrySttm.actNum, "");
			if (actItem != null) {
				FtpSet ftpSet = bankFront.getFtpSet("");
				
				WriteBankLogLn2("微保单笔实时代收付对账单SFTP服务器地址:" + ftpSet.serverIP + ":" + ftpSet.port);
				
				String downFileName = actItem.merchantId + "_" + p_reqQrySttm.busDate + "_SINGLE.txt";
				WriteBankLogLn2("微保单笔实时代收付对账单所在服务器路径:" + getSFTPDir(ftpSet.downDir) + actItem.merchantId + "/" + downFileName);
				
	            String localFilePath = createTempFileDirectory() + File.separator + downFileName;
	            WriteBankLogLn2("微保单笔实时代收付对账单保存本地路径:" + localFilePath);
				
				SftpPortClient sftp = new SftpPortClient(ftpSet);
	            FtpReceiver ftpReceiver = sftp.downloadFile(actItem.merchantId + "/", downFileName, localFilePath);
	            if (ftpReceiver.isCompleted) {
	            	WriteBankLogLn2("微保单笔实时代收付对账单下载成功!");
	            	
	            	String tmpStrRet = FileHelper.readFileText(localFilePath, getCharset());
	            	WriteBankLogLn2("微保单笔实时代收付对账单响应数据:\r\n" + tmpStrRet);
	            	if (StringHelper.hasAnyChar(tmpStrRet)) {
	            		StringReader strReader = new StringReader(tmpStrRet);
						BufferedReader tmpReader = new BufferedReader(strReader);
						
						String totalLine = tmpReader.readLine();
						retAts.totalNum = new BigDecimal(totalLine.split("\\|")[2]).add(new BigDecimal(totalLine.split("\\|")[4])).toString();
						
						while(true) {
							String eachline = tmpReader.readLine();
							if(eachline == null){
								break;
							}
							
							String[] detailNodes = eachline.split("\\^");
							if ("1".equals(detailNodes[10])) {
								RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();
								
								if (StringHelper.hasAnyChar(detailNodes[2])) {
									tmpRetDetail.askNumber = detailNodes[2];
								}
								
								if (StringHelper.hasAnyChar(detailNodes[3])) {
									String busType = detailNodes[3];
									if ("1".equals(busType)) {
										tmpRetDetail.cdFlag = "22";
									} else {
										tmpRetDetail.cdFlag = "27";
									}
								}
								
								if (StringHelper.hasAnyChar(detailNodes[4])) {
									tmpRetDetail.amount = detailNodes[4];
								}
								
								tmpRetDetail.busTime = Format.DateTime14Format.format(p_reqQrySttm.getBusDate());
								
								if (StringHelper.hasAnyChar(detailNodes[8])) {
									tmpRetDetail.oppAct = detailNodes[8];
								}
								
								if (StringHelper.hasAnyChar(detailNodes[5])) {
									tmpRetDetail.oppActName = detailNodes[5];
								}
								
								tmpRetDetail.transState = TransState.Success;
			    				
				        		retAts.writeRetDetail(tmpRetDetail);
							}
						}
	            	} else {
	            		respCode = "-1";
		    			respInfo = "微保单笔实时代收付对账单内容为空,请联系微保相关技术人员!";
	            	}
	            } else {
	            	respCode = "-1";
	    			respInfo = "微保单笔实时代收付对账单下载失败,原因:\r\n" + ftpReceiver.connMsg;
	            }
			} else {
				respCode = "-1";
				respInfo = "未找到账号[" + p_reqQrySttm.actNum + "]商户配置信息!";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			respCode = "-1";
			respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		respHeader[0] = respCode;
		respHeader[1] = respInfo;
		
		return respHeader;
	}
}
